package org.hy.pay.message.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SystemProperties {

	private static final Logger logger = LoggerFactory.getLogger(SystemProperties.class);
	
	private static final Map<String, SystemProperties> propertiesMap = new HashMap<String, SystemProperties>();
	
	private Properties properties;

	private SystemProperties(Properties properties, String path) {
		this.properties = properties;
		loadPropertiesFile(path);
	}

	/**
	 * 加载配置文件
	 * @param path
	 */
	private void loadPropertiesFile(String path) {
		InputStream is = null;
		try {
			is = SystemProperties.class.getClassLoader().getResourceAsStream(path);
			this.properties.load(is);
		} catch (Exception e) {
			logger.error("load properties file error:", e);
		}finally{
			if(null != is){
				try {
					is.close();
				} catch (IOException e) {
					logger.error("io exception:", e);
				}
			}
		}
	}
	
	/**
	 * 返回SystemProperties的对象
	 * @param path
	 * @return
	 */
	public static SystemProperties getInstance(String path){
		SystemProperties systemProperties = propertiesMap.get(path);
		if(null == systemProperties){
			systemProperties = getInstanceFactory(path);
		}
		return systemProperties;
	}
	
	/**
	 * 实例工厂
	 * @param path
	 * @return
	 */
	private static SystemProperties getInstanceFactory(String path){
		synchronized (SystemProperties.class) {
			SystemProperties systemProperties = propertiesMap.get(path);
			if(null == systemProperties){
				Properties p = new Properties();
				systemProperties = new SystemProperties(p, path);
				propertiesMap.put(path, systemProperties);
			}
			return systemProperties;
		}
	}
	
	/**
	 * 返回properties文件中属性的值
	 * @param key
	 * @return
	 */
	public String getProperty(String key){
		return (String) this.properties.get(key);
	}
}
